const express = require('express');
const router = express.Router();
const {Category,Course} = require('../../models');
const {Op} = require('sequelize');
const { NotFoundError } = require('../../utils/errors');
const { Success, failure } = require('../../utils/responses');
const {get} = require("axios");

//获取所有分类列表
router.get('/', async (req, res) => {
    try {
        const query = req.query;
        //分页查询需要的参数
        const currentPage = Math.abs(query.currentPage) || 1;
        const pageSize = Math.abs(query.pageSize) || 10;
        const offset = (currentPage - 1) * pageSize;

        const condition = {
            order: [["id", "ASC"],['rank','ASC']],
            offset: offset,
            limit: pageSize
        };
        if (query.name) {
            condition.where = {
                name: {
                    [Op.like]: `%${query.name}%`
                }
            };
        }


        const categories = await Category.findAndCountAll(condition);
        Success(res, '分类查询成功', {
            rows: categories.rows,
            pagination: {
                total: categories.count,
                currentPage: currentPage,
                pageSize: pageSize
            }
        });
    } catch (err) {
        failure(res, err);
    }
});
//获取指定分类
router.get('/:id', async (req, res) => {
    try {

        const category = await GetCategory(req);
        Success(res, '获取分类成功', category);
    } catch (err) {
        failure(res, err);
    }
});
//创建分类
router.post('/', async (req, res) => {
    try {

        //白名单过滤
        const body = FilterBody(req);
        const category = await Category.create(body);

        Success(res, '创建分类成功', category, 201);
    } catch (error) {
        console.log("错误信息：", error);

        failure(res, error);

    }
});
//更新分类
router.put('/:id', async (req, res) => {
    try {
        const category = await GetCategory(req);
        await category.update(req.body);
        Success(res, '更新成功！', category, 200)
    } catch (err) {
        failure(res, err);
    }
});

//删除分类
router.delete('/:id', async (req, res) => {
    try {
        const category = await GetCategory(req);

        const count = await Course.count({where:{categoryId:req.params.id}});
        if (count>0) {
            throw new Error('当前分类有课程，无法删除');
        }

        await category.destroy();
        Success(res, '删除成功');

    } catch (err) {
        failure(res, err);
    }
});


/**
 * 白名单过滤
 * @param req
 * @returns {{name, rank: (number|*)}}
 * @constructor
 */
function FilterBody(req) {
    return body = {
        name: req.body.name,
        rank: req.body.rank
    };
}

//获取category对象
async function GetCategory(req) {
    const {id} = req.params;
    const category = await Category.findByPk(id);
    if (!category) {
        throw new NotFoundError(`ID:${id}的分类未找到`);
    }
    return category;
}

module.exports = router;